﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using OpenSoftStore.BusinessLogic.Service;
using OpenSoftStore.Client.Common;
using OpenSoftStore.Orm.Model;
using OpenSoftStore.Orm.View;
using OpenSoftStore.BusinessLogic.Common;
using OpenSoftStore.Client.UIL.ManageCommon;
using OpenSoftStore.BusinessLogic.Product;
using OpenSoftStore.Orm;

namespace OpenSoftStore.Client.UIL.ManageService
{
    public partial class ServiceAdd : UserControl
    {
        private static ServiceLogic serviceBll = new ServiceLogic();
        private static ProductLogic productBll = new ProductLogic();
        private static ComboLogic comboBll = new ComboLogic();
        private T_Product service;
        private T_ProductExt productExt;
        private V_Product serviceView;
        private List<V_Product> productsView;
        private FormTreeSelecter formTreeSelecter = new FormTreeSelecter();
        public Boolean Drog = false;
        public int Top = 0;
        public int Left = 0;

        public ServiceAdd()
        {
            service = new T_Product();
            productExt = new T_ProductExt();
            serviceView = new V_Product();
            productsView = new List<V_Product>();
            InitializeComponent();
            LoadControlData();
        }


        private void ServiceAdd_Load(object sender, EventArgs e)
        {
            txtServiceNo.Focus();
            txtServiceNo.Select();
        }

        private void LoadControlData()
        {
            ComboLogic comboBll = new ComboLogic();
            cmbBrokerageType.DisplayMember = "DisplayText";
            cmbBrokerageType.ValueMember = "Value1";
            cmbBrokerageType.DataSource = comboBll.GetComboByBuzType("BrokerageType");

            txtServiceNo.Text = serviceBll.GetCountNo("T_Product", false);
            //txtServType.Text = ServiceList.Instance.tvService.SelectedNode.Text;
            //service.TreeId = ServiceList.Instance.tvService.SelectedNode.Name;
            dgvProduct.AutoGenerateColumns = false;
            dgvProduct.DataSource = productBll.GetProductDataTable();
            dgvServiceAndProduct.AutoGenerateColumns = false;
            SPACommon.SetDataGridStyle(dgvProduct);
            SPACommon.SetDataGridStyle(dgvServiceAndProduct);
        }

        private void tsbSave_Click(object sender, EventArgs e)
        {
            var table = (DataTable)dgvServiceAndProduct.DataSource ?? new DataTable();
            if (CheckInput())
            {
                SetValue();
                if (string.IsNullOrEmpty(serviceView.Id))
                {
                    service.Id = Guid.NewGuid().ToString("D");
                    productExt.ExtId = Guid.NewGuid().ToString("D");
                    productExt.ProductId = service.Id;
                    serviceBll.AddService(service, productExt, table);
                    //FormSysMessage.ShowSuccessMsg("添加成功！");
                }
                else
                {
                    serviceBll.UpdateService(service, productExt, table);
                    //FormSysMessage.ShowSuccessMsg("修改成功！");
                }

                this.FindForm().Close();

                ServiceList.Instance.btnSearch_Click(null, null);
            }
        }

        private bool CheckInput()
        {
            if (string.IsNullOrEmpty(txtServiceNo.Text.Trim()))
            {
                FormSysMessage.ShowMessage("请输入服务编号！");
                return false;
            }
            if (string.IsNullOrEmpty(txtServName.Text.Trim()))
            {
                FormSysMessage.ShowMessage("请输入服务名称！");
                return false;
            }
            if (string.IsNullOrEmpty(txtServType.Text.Trim()))
            {
                FormSysMessage.ShowMessage("请选择服务类型！");
                return false;
            }
            return true;
        }

        private void SetValue()
        {
            service.Name = txtServName.Text.Trim();
            service.IsProject = "是";
            service.ProductNo = txtServiceNo.Text.Trim();
            service.ShortName = txtShortName.Text.Trim();

            if (service.Id != null)
            {
                productExt = serviceBll.Where<T_ProductExt>(s => s.ProductId == service.Id).FirstOrDefault();
            }
            productExt = productExt ?? new T_ProductExt();
            productExt.SalePrice = numServPrice.Value;
            productExt.BrokerageNum = numBrokerageNum.Value;
            productExt.BrokerageType = cmbBrokerageType.Text.Trim();
            productExt.BarCode = txtBarCode.Text.Trim();

        }

        public void GetService(string id)
        {
            service.Id = id;//给Id赋值，判断新增还是修改

            serviceView = serviceBll.GetServiceView(" and P.Id='" + id + "'").FirstOrDefault();
            txtServName.Text = serviceView.Name;
            txtServiceNo.Text = serviceView.ProductNo;
            txtShortName.Text = serviceView.ShortName;
            txtBarCode.Text = serviceView.BarCode;
            txtServType.Text = serviceView.TreeName;
            numBrokerageNum.Value = serviceView.BrokerageNum;
            numServPrice.Value = serviceView.SalePrice;
            cmbBrokerageType.DisplayMember = "DisplayText";
            cmbBrokerageType.ValueMember = "Value1";
            cmbBrokerageType.DataSource = comboBll.GetComboByBuzType("BrokerageType");
            cmbBrokerageType.Text = serviceView.BrokerageType;
            dgvServiceAndProduct.DataSource = serviceBll.GetServiceAndProductTable(" where S.ServiceId='" + service.Id + "'");
        }

        public void SetTreeValue(string treeId, string treeName)
        {
            service.TreeId = treeId;
            txtServType.Text = treeName;
        }

        private void BtnCancel_Click(object sender, EventArgs e)
        {
            this.FindForm().Close();
        }

        private void pbClose_Click(object sender, EventArgs e)
        {
            this.FindForm().Close();
        }

        private void btnType_Click(object sender, EventArgs e)
        {
            FormTreeSelecter formTreeSelecter = new FormTreeSelecter();
            formTreeSelecter.GetTreeByType("ProjectTree");
            formTreeSelecter.ShowDialog();
            if (formTreeSelecter.DialogResult != DialogResult.OK) return;

            service.TreeId = formTreeSelecter.TypeId;
            txtServType.Text = formTreeSelecter.TypeText;
        }

        private void btnAddItem_Click(object sender, EventArgs e)
        {
            var table = new DataTable("T_ServiceWithProduct");
            table.Columns.Add("Name", typeof(String));
            table.Columns.Add("ProductId", typeof(String));
            table.Columns.Add("Amount", typeof(Decimal));
            table.Columns.Add("Cost", typeof(Decimal));
            for (int i = 0; i < dgvProduct.Rows.Count; i++)
            {
                if (dgvProduct.Rows[i].Cells["IsChecked"].Value == null)
                {
                    continue;
                }
                if (dgvProduct.Rows[i].Cells["IsChecked"].Value.ToString() == "是")
                {
                    var row = table.NewRow();

                    row["Name"] = dgvProduct.Rows[i].Cells["name"].Value.ToString();
                    row["ProductId"] = dgvProduct.Rows[i].Cells["productId"].Value.ToString();
                    row["Amount"] = Convert.ToDecimal(dgvProduct.Rows[i].Cells["subAmount"].Value);
                    row["Cost"] = Convert.ToDecimal(dgvProduct.Rows[i].Cells["inPrice"].Value);
                    table.Rows.Add(row);
                }
            }
            dgvServiceAndProduct.DataSource = table;
        }

        private void btnDeleteItem_Click(object sender, EventArgs e)
        {
            if (dgvServiceAndProduct.CurrentRow == null)
            {
                return;
            }
            dgvServiceAndProduct.Rows.RemoveAt(dgvServiceAndProduct.CurrentRow.Index);
        }

        private void txtProductSearch_KeyUp(object sender, KeyEventArgs e)
        {
            string searchText = txtProductSearch.Text.Trim();
            string whereStr = string.Format(" and P.Name like '{0}%' or T.Name like '{0}%'", searchText);
            dgvProduct.DataSource = productBll.GetProductDataTable(whereStr);
        }

        private void dgvServiceAndProduct_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;
            string productId = dgvServiceAndProduct.Rows[e.RowIndex].Cells["colId"].Value.ToString();
            decimal useAmount = Convert.ToDecimal(dgvServiceAndProduct.Rows[e.RowIndex].Cells["colAmount"].Value);
            var product = serviceBll.Where<T_ProductExt>(p => p.ProductId == productId).FirstOrDefault();
            var subAmount = product.SubAmount == 0 ? 1 : product.SubAmount;
            decimal cost = product.InPrice / subAmount * useAmount;
            dgvServiceAndProduct.Rows[e.RowIndex].Cells["colCost"].Value = cost;
        }

        private void PnlInfoTitle_MouseDown(object sender, MouseEventArgs e)
        {
            Drog = true;
            Top = e.Y;
            Left = e.X;
        }

        private void PnlInfoTitle_MouseMove(object sender, MouseEventArgs e)
        {
            if (!Drog) return;
            var findForm = FindForm();
            if (findForm == null) return;
            findForm.Top += e.Y - Top;
            findForm.Left += e.X - Left;
        }

        private void PnlInfoTitle_MouseUp(object sender, MouseEventArgs e)
        {
            Drog = false;
        }

        bool flag = false;
        private void btnAll_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < dgvProduct.Rows.Count; i++)
            {
                if (flag == true)
                {
                    dgvProduct.Rows[i].Cells["IsChecked"].Selected = false;
                    dgvProduct.Rows[i].Cells["IsChecked"].Value = "否";
                }
                else
                {
                    dgvProduct.Rows[i].Cells["IsChecked"].Selected = true;
                    dgvProduct.Rows[i].Cells["IsChecked"].Value = "是";
                }

            }
            flag = flag == true ? false : true;
        }
    }
}
